package com.zbo.service;

import com.zbo.mapper.StudentMapper;
import com.zbo.pojo.Student;
import com.zbo.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class StudentService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 学生登录验证
     *
     * @param username 用户名
     * @param password 密码（明文，开发阶段）
     * @return 登录成功的 Student 对象，失败返回 null
     */
    public Student login(String username, String password) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            Student student = mapper.selectByUsername(username);

            if (student != null && password != null &&
                    password.equals(student.getPassword())) {
                return student;
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            session.close();
        }
    }

    /**
     * 检查用户名是否已存在（用于注册）
     *
     * @param username 用户名
     * @return true=已存在, false=可用
     */
    public boolean isUsernameExists(String username) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            Student student = mapper.selectByUsername(username);
            return student != null;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    /**
     * 注册新学生
     *
     * @param username 用户名
     * @param password 密码（明文）
     * @return 注册成功返回 true
     */
    public boolean register(String username, String password) {
        // 写操作：关闭自动提交
        SqlSession session = sqlSessionFactory.openSession(false);
        try {
            StudentMapper mapper = session.getMapper(StudentMapper.class);

            // 检查用户名是否重复
            if (isUsernameExists(username)) {
                return false;
            }

            // 创建学生对象
            Student student = new Student();
            student.setUsername(username);
            student.setPassword(password); // 明文存储

            // 插入数据库
            mapper.insert(student);
            session.commit(); // 提交事务
            return true;
        } catch (Exception e) {
            session.rollback(); // 回滚
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    public String getUsernameById(Integer studentId) {
        if (studentId == null) {
            return null;
        }
        try (SqlSession session = sqlSessionFactory.openSession()) {
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            return mapper.selectUsernameById(studentId);
        }
    }
}
